package xin.nick.roc.consumer.client;

import io.netty.util.internal.StringUtil;
import lombok.Data;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Nick
 * @date 2021/7/4
 * @description
 */
@Data
public class ProviderInfo {
    private static List<RpcClient> rpcClientList = new ArrayList<>();
    private static AtomicInteger atomicInteger = new AtomicInteger();
    private static Map<String, Long> responseTimeMap = new HashMap<>();
    private static Map<String, RpcClient> rpcClientMap = new HashMap<>();

    private String ip;
    private int port;

    public static RpcClient getRpcClientInfo() {
        String path = "/provider";
        // 从zk里面拿最新的列表,根据响应时间取最小的
        try {
            List<String> providerList = ZkRegister.getClient().getChildren().forPath(path);
            String finalProvider = "";
            Long minTime = Long.MAX_VALUE;
            for (String provider : providerList) {
                String timeString = new String(ZkRegister.getClient().getData().forPath(path + "/" + provider));
                String[] timeArray = timeString.split(" ");
                Long responseTime = Long.parseLong(timeArray[1]);
                if(minTime >= responseTime) {
                    minTime = responseTime;
                    finalProvider = provider;
                }
            }
            // 如果没选出最小的,就随机来个
            if(StringUtil.isNullOrEmpty(finalProvider)) {
                finalProvider = providerList.get(new Random().nextInt(providerList.size()));
            }
            return rpcClientMap.get(finalProvider);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<RpcClient> getRpcClientList() {
        return rpcClientList;
    }

    public static void setRpcClientList(List<RpcClient> rpcClientList) {
        ProviderInfo.rpcClientList = rpcClientList;
    }

    public static Map<String, Long> getResponseTimeMap() {
        return responseTimeMap;
    }

    public static Map<String, RpcClient> getRpcClientMap() {
        return rpcClientMap;
    }

    public static void setRpcClientMap(Map<String, RpcClient> rpcClientMap) {
        ProviderInfo.rpcClientMap = rpcClientMap;
    }
}
